import { GridService } from '@service/grid.service';
import { AbsFormUtil } from '@abstract/form';
import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormControl, Validators } from '@angular/forms';
import { GenderList } from '@app/store/dict';
import { BaseService } from '@service/base.service';
import { TreeService } from '@service/tree.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { NzTreeNode } from 'ng-zorro-antd/tree';
import { DatePipe } from '@angular/common';
@Component({
	selector: 'app-grid-list-edit',
	templateUrl: './grid-list-edit.component.html',
	styleUrls: ['./grid-list-edit.component.less'],
	providers: [DatePipe]
})
export class GridListEditComponent extends AbsFormUtil implements OnInit {
	@Input() id: string;
	@Input() griderType: string;

	genderList = GenderList;
	areaAddrOptions = [];
	areaList = [];

	areaInfoList = [];
	householdList = [];
	griderMinilist = [];

	householdByGriderList = [];
	// gongTree = [];
	constructor(
		private nzMessageService: NzMessageService,
		private fb: FormBuilder,
		private nzModalRef: NzModalRef,
		private baseService: BaseService,
		private treeService: TreeService,
		private gridService: GridService,
		private datePipe: DatePipe
	) {
		super();
	}

	ngOnInit() {
		this.buildForm();
		this.getCommunityTree();

		this.init();



	}

	init() {
		// 1专职网格长 还是原来的1和2步骤，选社区，选网格 都是单选， 第三步根据网格区获取微网格员列表，多选
		// 2网格员：1获取社区树 2根据社区获取网格区信息 

		// 3 微网格长 1获取社区树 2根据社区获取网格区信息  3根据网格获取村户列表
		//  gridRegion 网格区ID 只有2网格员才有这个字段  gridRegion 
		// areaSave areas	楼栋
		if (['1', '3'].includes(this.griderType)) {
			this.validateForm.addControl('areaSave', this.fb.control([], Validators.required));
			this.validateForm.addControl('areas', this.fb.control([],));
		}
	}




	buildForm() {
		this.validateForm = this.fb.group({
			gender: ['', Validators.required],
			contractNumber: ['', [Validators.required, this.phomeValidator]],
			birthdate: [''],
			name: ['', Validators.required],
			ownerCommunity: ['', Validators.required],
			gridRegion: ['', Validators.required]
		});
	}
	phomeValidator = (control: FormControl): { [s: string]: boolean } => {
		const reg = /^1[3|4|5|7|8][0-9]{9}$/; //验证规则
		if (control.value ) {
			if (!reg.test(control.value)) {
				return { phoneNum: true, error: true  };
			}
		} 
	}

	onSubmit() {
		this.markAsDirty();
		if (this.validateForm.invalid) {
			return;
		}
		const formValue = this.validateForm.value;
		formValue.birthdate = this.datePipe.transform(formValue.birthdate, 'yyyy-MM-dd');

		return {...formValue};
	}
	destroyModal() {
		this.nzModalRef.destroy();
	}

	ownerCommunityChange(val) {
		const areaId = val[val.length - 1];
		this.gridAreaInfoByCommunity(areaId);
		this.getFormControl('gridRegion')?.setValue('');
		if (['1', '3'].includes(this.griderType)) {
			this.getFormControl('areaSave')?.setValue([]);
		}
		
	}
	// 配置网格区
	gridRegionChange(gridRegion) {
		if (!gridRegion){
			return;
		}
		if (this.griderType === '1') {
			// 根据网格区获取微网格员列表，多选
			this.getGriderMinilist(gridRegion);
			this.getFormControl('areaSave')?.setValue([]);
		}
		if (this.griderType === '3') {
			// 据网格获取村户列表 多选
			this.getHouseholdListByGridArea(gridRegion);
			this.getFormControl('areaSave')?.setValue([]);
		}
	}
	nzDisplayWith = (node: NzTreeNode) => {
		if (node?.parentNode?.origin) {
			return node.parentNode.origin.title + '-' + node.title;
		}
		return node.title;
	}
	

	private async getGriderInfo() {
		const result = await this.gridService.getGriderInfo(this.griderType, this.id);
		const griderInfo = result.data;
		const areaItem = this.areaList.find(itm => itm.id === String(griderInfo.ownerCommunity));
		griderInfo.ownerCommunity = areaItem ? this.getAreaId(areaItem, [String(griderInfo.ownerCommunity)]) : '';
		griderInfo.areaSave = griderInfo.areas ? griderInfo.areas : [];
		// griderInfo.areas = [];
		this.validateForm.patchValue(griderInfo);
	}
	private async getCommunityTree() {
		const result = await this.baseService.getCommunityTree();
		this.areaList = result.data;
		this.areaList.forEach(it => {
			it.label = it.areaFullName;
			it.value = it.id;
			it.isLeaf = !this.areaList.some(itm => itm.parentId == it.id);
		});
		if (this.id) {
			this.getGriderInfo();
		}
		this.areaAddrOptions = this.treeService.convertListToTree(this.areaList, 0);
	}

	private async gridAreaInfoByCommunity(areaId: string) {
		const result = await this.gridService.gridAreaInfoByCommunity(areaId);
		this.areaInfoList = result.data;
	}
	/**
	 * 根据微网格长获取村户列表
	 * @param id 
	 */
	private async getHouseholdListByGridArea(id: string) {
		const result = await this.gridService.getHouseholdListByGridArea(id);
		this.householdList = result.data;
	}
	/**
	 * 根据网格区获取微网格员列表
	 * @param id 
	 */
	private async getGriderMinilist(id: string)  {
		const result = await this.gridService.getGriderMinilist(id);
		result.data.forEach(it => { it.id = Number(it.id);});
		this.griderMinilist = result.data;
			// this.getFormControl('areaSave').setValue([]);
			// const areaSaveVal = this.getFormControl('areaSave').value();
			// let isReset = false;
			// areaSaveVal.forEach(itm => {
			// 	if () {

			// 	}
			// });

	}
	// private async getDongTree(areaId: string) {
	// 	const result = await this.gridService.getDongTree(areaId);
	// 	const gongList = result.data.filter(Boolean);
	// 	let parentId = null;
	// 	gongList.forEach(item => {
	// 		item.title = item.areaFullName;
	// 		item.value = Number(item.id);
	// 		item.key = Number(item.id);
	// 		item.isLeaf = !gongList.some(itm => itm.parentId == item.id);
	// 		if (gongList.some(itm => itm.parentId == item.id) && !parentId) {
	// 			parentId = item.parentId;
	// 		}
	// 	});
	// 	this.gongTree = this.treeService.convertListToTree(gongList, parentId);
	// }
	getAreaId(area, result: string[]) {
		const areaItem = this.areaList.find(itm => itm.id === String(area.parentId));
		if (areaItem) {
			result.unshift(String(areaItem.id));
			if (areaItem.parentId) {
				return this.getAreaId(areaItem, result);
			}
			return result;
		}
	}
	griderMinilistChange(ids: number[]) {
		this.householdByGriderList = [];
		if (ids) {
			ids.forEach(id => {
				this.getHouseholdListByGrider(id);
			});
		};
	}
	private async getHouseholdListByGrider(id) {
		const result = await this.gridService.getHouseholdListByGrider(id);
		this.householdByGriderList = [...this.householdByGriderList, ...result.data];
	}
	householdReset() {
		this.getFormControl('areaSave').setValue([]);
	}
}
